﻿using Microsoft.AspNetCore.Authorization;

namespace HMS.TenantServer.Authorization;

public class TenantAuthorizationHandler : AuthorizationHandler<TenantAuthorizationRequirement>
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TenantAuthorizationRequirement requirement)
    {
        if (requirement.License != null && context.User.HasClaim(x =>
            x.Type == "tenant:license" && requirement.License.Equals(x.Value)))
        {
            context.Succeed(requirement);
        }
        else if (requirement.IsRoot != null && context.User.HasClaim(x =>
            x.Type == "tenant:isroot" && requirement.IsRoot == bool.Parse(x.Value)))
        {
            context.Succeed(requirement);
        }
        else
        {
            context.Fail();
        }

        return Task.CompletedTask;
    }
}